# an automatically applied search. reports matching this search are automatically marked important.
class Rule < ActiveRecord::Base
  belongs_to(:search)
  
  # applies all rules in a transaction
  def self.apply_all
    transaction do
      cutoff = (Time.now.utc - 1.hour).basic_format
      # apply 
      all.each{|a| a.apply(cutoff)}
      # mark scanned
      mark_scanned(cutoff)
    end
  end
  
  # marks all unscanned reports after cutoff as scanned
  def self.mark_scanned(cutoff)
    connection.execute("update reports set is_autoscanned=1 where is_autoscanned is null and reports.created_at > '#{cutoff}'")
  end
  
  # run the associated search query
  def query
    search.query rescue nil
  end
  
  # applies the rule to all unscanned reports after cutoff
  def apply(cutoff)
    # get the search condition
    cond = Search.find(search_id).conditions
    # run the query
    connection.execute("update reports, sources set important='auto' 
      where reports.created_at > '#{cutoff}'
      and reports.source_id=sources.id
      and reports.is_autoscanned is null and reports.important is null and (#{cond})")
  end
end
